import Vue from 'vue'
import VueRouter from 'vue-router'
import menuList from '@/utils/menuList'
import { _import } from '@/utils'
// 在重写push|replace方法时，先把VueRouter原型对象的push|replace保存一份
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
// 参数1：告诉原来的push | replace方法，你往那里跳转（传递那些参数）
// 参数2：成功回调
// 参数3：失败回调
VueRouter.prototype.push = function(location, resolve, reject) {
	if (resolve && reject) {
		originPush.call(this, location, resolve, reject)
	} else {
		originPush.call(this, location, () => {}, () => {})
	}
}
VueRouter.prototype.replace = function(location, resolve, reject) {
	if (resolve && reject) {
		originReplace.call(this, location, resolve, reject)
	} else {
		originReplace.call(this, location, () => {}, () => {})
	}
}


Vue.use(VueRouter)



// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
// const _import = require('./import-' + process.env.NODE_ENV)
// 生产环境的为 file => () => import('@/views/' + file + '.vue')


// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
	{
		path: '/login',
		component: _import('LoginView'),
		name: 'login',
		meta: {
			title: '登录'
		}
	}
]
// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
	path: '/',
	component: _import('MainView'),
	name: 'main',
	redirect: {
		name: 'home'
	},
	meta: {
		title: '主入口整体布局'
	},
	children: menuList
}

const router = new VueRouter({
	mode: 'hash',
	scrollBehavior: () => ({
		y: 0
	}), // 当切换到新路由时，想要页面滚到顶部
	isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
	routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
	// 添加动态(菜单)路由
	// 1. 已经添加 or 全局路由, 直接访问
	// 2. 获取菜单列表, 添加并保存本地存储
	// fnCurrentRouteType为判断当前路由类型的函数
	let userInfo = sessionStorage.getItem('userInfo')
	if (to.name==='login'||userInfo) {
		console.log(1);
		next()
	} else {
		router.push({
			name: 'login'
		})
	}
})




export default router
